package com.example.radioplayer;

import java.util.List;
import java.util.Random;

import com.example.radioplayer.MusicLoader.Ablum;
import com.example.radioplayer.MusicLoader.Music;
import com.example.radioplayer.MusicLoader.MusicLibary;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class RadioPlayerService extends Service {
	private static final String TAG = RadioPlayerService.class.getName();

	private static final int NORMOL = 0;
	private static final int RANDOM = 1;
	
	private MediaPlayer mMediaPlayer;
	
	private Binder musicBinder = new MusicBinder(); 
	
	private boolean isPlaying = false; //defalut music play status
	
	private MusicLibary musicLibrary;
	private Ablum ablum;
	
	private int currentAblum=0;
	private int currentMusic=0;
	private int currentPosition=0;
	
	private int playMode = RANDOM;
	
	private static final int updateProgress = 1;
	private static final int updateCurrentMusic = 2;
	private static final int updateDuration = 3;
	
	public static final String ACTION_UPDATE_PROGRESS = "com.anytum.mobipao.UPDATE_PROGRESS";
	public static final String ACTION_UPDATE_DURATION = "com.anytum.mobipao.UPDATE_DURATION";
	public static final String ACTION_UPDATE_CURRENT_MUSIC = "com.anytum.mobipao.UPDATE_CURRENT_MUSIC";
	public static final String ACTION_ABLUM_NAME = "com.anytum.mobipao.ACTION_ABLUM_NAME";
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what){
			case updateProgress:
				toUpdateProgress();
			break;
			case  updateDuration:
				toUpdateDuration();
			break;
			case updateCurrentMusic:
				toUpdateCurrentMusic();
			break;
			}
		
		}
		
	}; 
	
	private void toUpdateDuration() {
		// TODO Auto-generated method stub
		if(mMediaPlayer != null){					
			int duration = mMediaPlayer.getDuration();					
			Intent intent = new Intent();
			intent.setAction(ACTION_UPDATE_DURATION);
			intent.putExtra(ACTION_UPDATE_DURATION,duration);
			sendBroadcast(intent);									
		}
	
	}

	private void toUpdateProgress() {
		// TODO Auto-generated method stub
		if(mMediaPlayer != null && isPlaying){
			int progress = mMediaPlayer.getCurrentPosition();
			Intent intent = new Intent();
			intent.setAction(ACTION_UPDATE_PROGRESS);
			intent.putExtra(ACTION_UPDATE_PROGRESS, progress);
			sendBroadcast(intent);
			mHandler.sendEmptyMessageDelayed(updateProgress, 1000);
		}
	}
	
	private void toUpdateCurrentMusic(){
		Intent intent = new Intent();
		intent.setAction(ACTION_UPDATE_CURRENT_MUSIC);
		intent.putExtra(ACTION_UPDATE_CURRENT_MUSIC,currentMusic);
		intent.putExtra(ACTION_ABLUM_NAME,musicLibrary.ablums.get(currentAblum).name);
		sendBroadcast(intent);				
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return musicBinder;
	}
	
	

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		initMediaPlayer();
		musicLibrary = MusicLoader.instance(getContentResolver()).getMusicLibary();
		ablum = musicLibrary.ablums.get(currentAblum);
		
		Log.d(TAG,"[Service ] MusicService creare and Music Load comp");
	}

	public void onDestroy(){
		if(mMediaPlayer != null){
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

	public class MusicBinder extends Binder{
		public void setAblum(int pcurrentAblum){
			currentAblum = pcurrentAblum;
		}
		
		public void toLocalAblum(int position){
			stop();
			currentAblum = position;
			play(currentAblum, currentMusic, 0 );
		}
		public void setPlayMode(int pplaymode){
			playMode = pplaymode;
		}
		public void setIsplay(boolean flag){
			isPlaying = flag;
		}
		
		public void startPlay(){
			play(currentAblum,currentMusic,currentPosition);
		}
		
		public void stopPlay(){
			stop();
		}
		public void toNextAblum(){
			nextAblum();
		}
		
		public void toPreviousAblum(){
			previousAblum();
		}
		
		
		public void toNextMusic(){
			playNext();
		}
		public void toPreviousMusic(){
			playPrevious();
		}
		public boolean isPlaying() {
			// TODO Auto-generated method stub
			return isPlaying;
		}
		
	}

	private void nextAblum() {
		// TODO Auto-generated method stub
		stop();
		currentAblum = (currentAblum+1) % musicLibrary.ablums.size();
		ablum =  musicLibrary.ablums.get(currentAblum);
		currentMusic = (int)(Math.random()*ablum.musics.size());
		play(currentAblum,currentMusic,0);
	
	}
	private void previousAblum() {
		// TODO Auto-generated method stub
		stop();
		if(currentAblum - 1 < 0){
			Log.d(TAG, "this is the first ablum in this musicLibary");
		}else{
			currentAblum = (currentAblum-1) % musicLibrary.ablums.size();
			ablum =  musicLibrary.ablums.get(currentAblum);
			currentMusic = (int)(Math.random()*ablum.musics.size());
			play(currentAblum,currentMusic,0);
		}
	}
	
	/**
	 * initialize the MediaPlayer
	 * */
	private void initMediaPlayer(){
		mMediaPlayer = new MediaPlayer();
		mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer arg0) {
				// TODO Auto-generated method stub
				if(isPlaying){
					Log.d(TAG,"[OnPreparedListener] Start at " + currentMusic  + ", currentPosition : " + currentPosition);
					mMediaPlayer.start();
					mMediaPlayer.seekTo(currentPosition);
					Log.d(TAG, "[OnPreparedListener] Start at " + currentMusic  + ", currentPosition : " + currentPosition);
					mHandler.sendEmptyMessage(updateDuration);
				}
			
			}
		});
	
		mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer arg0) {
				// TODO Auto-generated method stub
				Log.d(TAG, "[OnCompletionListener] On Completion at " + currentMusic);
				play(currentAblum,(currentMusic + 1) % ablum.musics.size(), 0);
			
			}
		});
	}
	
	
		private void play(int pcurrentAblum, int pcurrentMusic, int pcurrentPosition){
			// 判断播放模式，有随机播放是顺序播放两中模式
			switch(playMode){
				case NORMOL:
					currentPosition = pcurrentPosition;
					setCurrentMusic(currentMusic);
					currentAblum = pcurrentAblum;
					break;
				case RANDOM:
					currentPosition = pcurrentPosition;
					currentAblum = pcurrentAblum;
					currentMusic = (int)(musicLibrary.ablums.get(currentAblum).musics.size()*Math.random());
					break;
			}

			mMediaPlayer.reset();
			try {
				mMediaPlayer.setDataSource(musicLibrary.ablums.get(pcurrentAblum).musics.get(pcurrentMusic).url);
				mHandler.sendEmptyMessage(updateCurrentMusic);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.e(TAG,"[MediaPlayer DataSource] music url"+ablum.musics.get(currentMusic).url+"currentMusic: "+currentMusic+"have error");
			}
			Log.d(TAG, "[Play] Start Preparing at" + currentMusic);
		mMediaPlayer.prepareAsync();
			mHandler.sendEmptyMessage(updateProgress);
			
			isPlaying = true;
		
		}
		
		
		private void stop(){
			currentPosition =  mMediaPlayer.getCurrentPosition();
			mMediaPlayer.stop();
			isPlaying = false;
		}
		
		private void playNext(){
			stop();
			currentMusic = (currentMusic + 1 )% musicLibrary.ablums.size();
			play(currentAblum, currentMusic, 0);
		}
		
		private void playPrevious(){
			if(currentMusic - 1 < 0){
				Log.d(TAG, "this is the first music in this ablum");
			}else{
				stop();
				play(currentAblum,currentMusic,0);
			}
		}
		
		private void setCurrentMusic(int pCurrentMusic) {
			// TODO Auto-generated method stub
			currentMusic = pCurrentMusic;
			mHandler.sendEmptyMessage(updateCurrentMusic);
		}
}
